package spring.cloud.tasks.tasks_manager.tasks_manager.listener;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type;
import spring.cloud.tasks.tasks_manager.tasks_manager.node.Node;
import spring.cloud.tasks.tasks_manager.tasks_manager.service.AllotTaskItemService;
import spring.cloud.tasks.tasks_manager.tasks_manager.service.TreeCacheService;

/**
 * Job Server上下线Listener，会检测/status节点的添加和删除行为。
 */
@Slf4j
@Setter
@Getter
public class TaskExecutorsOnlineOfflineListener extends TreeCacheListener {

    private static final String NODE_STATUS = "/status";

    private static final int TREE_CACHE_DEPTH = 0;

    private String taskId;

    private String tatskExecutorNodePath;

    private TreeCacheService treeCacheService;

    private AllotTaskItemService allotTaskItemService;

    public TaskExecutorsOnlineOfflineListener(String taskId, TreeCacheService treeCacheService, AllotTaskItemService allotTaskItemService) {
        this.taskId = taskId;
        this.tatskExecutorNodePath = Node.getTaskExecutorsNodePath(taskId);
        this.treeCacheService = treeCacheService;
        this.allotTaskItemService = allotTaskItemService;
    }

    @Override
    public void childEvent(Type type, String path, String nodeData) throws Exception {
        if (path.equals(tatskExecutorNodePath)) {
            return;
        }
        String statusPath = path + NODE_STATUS;
        if (type == Type.NODE_ADDED) {
            treeCacheService.addTreeCacheIfAbsent(statusPath, TREE_CACHE_DEPTH);
            treeCacheService.addTreeCacheListenerIfAbsent(statusPath, TREE_CACHE_DEPTH, new TaskExecutorOnlineOfflineListener(taskId, allotTaskItemService));
        } else if (type == Type.NODE_REMOVED) { // 保证只watch新server clean事件
            treeCacheService.removeTreeCache(statusPath, TREE_CACHE_DEPTH);
        }
    }


}
